package com.xing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xing.DTO.UserRoleSaveDTO;
import com.xing.Utils.Result;
import com.xing.dao.SysUserRoleDao;
import com.xing.entity.SysRoleEntity;
import com.xing.entity.SysUserRoleEntity;
import com.xing.service.SysUserRoleService;
import com.xing.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleDao, SysUserRoleEntity> implements SysUserRoleService {

    @Autowired
    private SysUserRoleDao userRoleDao;


    @Override
    public List<Long> getRoleIdByUserId(Long userId) {
        return userRoleDao.getRoleIdByUserId(userId);
    }


    @Override
    @Transactional
    public Result saveUserRoleRelation(UserRoleSaveDTO userRoleSaveDTO) {
        // 获取用户id判断是否可用
        Long userId = userRoleSaveDTO.getUserId();
        if (userId == null) {
            return new Result().err(406, "缺少用户id");
        }
        // 删除用户原有角色
        LambdaQueryWrapper<SysUserRoleEntity> lambdaQueryWrapper = Wrappers.lambdaQuery(SysUserRoleEntity.class)
                .eq(SysUserRoleEntity::getUserId, userId);
        userRoleDao.delete(lambdaQueryWrapper);
        // 获取角色id进行判断
        Long roleId = userRoleSaveDTO.getRoleId();
        if (!(roleId == null)) {
            // 批量插入角色信息
            int insert = userRoleDao.insert(new SysUserRoleEntity(userId, roleId));
            // 返回操作结果
            if (insert >= 1) {
                return new Result().ok("更新成功");
            }
            return new Result().err(456, "更新失败");
        }
        return new Result().ok("更新成功");
    }


}
